import 'package:flutter/material.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';

class Profile {
  final int? id;
  final String name; // 地点
  final String time; // 时间
  final String rmb; // 人民币
  final int is_checkout; // 默认为0   1为未付款
  // 构造函数
  Profile({
    this.id,
    required this.name,
    required this.time,
    required this.rmb,
    required this.is_checkout,
  });
  // 将 Profile对象转换为Map
  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'name': name,
      'time': time,
      'rmb': rmb,
      'is_checkout': is_checkout,
    };
  }

  // 将Map转换为Profile对象
  factory Profile.fromMap(Map<String, dynamic> map) {
    return Profile(
      id: map['id'],
      name: map['name'],
      time: map['time'],
      rmb: map['rmb'],
      is_checkout: map['is_checkout'],
    );
  }
}

// getExternalStorageDirectory() ： 获取存储卡目录(仅安卓可用)
class Db {
  static const int dbVersion = 1;
  late String dbpath;
  late Database db;
  String table = "profile";
  String mapTable = "map";
  // 删除数据库
  Future deldb() async {
    await deleteDatabase(dbpath);
  }

  // 数据库初始化
  Future initdb() async {
    try {
      var databasesPath = await getExternalStorageDirectory();
      dbpath = join(databasesPath!.path, "demo.db");
      // dbpath = '${databasesPath!.path}/demo.db';

      // 档案表
      db = await openDatabase(
        dbpath,
        version: dbVersion,
        // 当打开数据库的时候创建一张表
        onCreate: (db, version) async {
          await db.execute(
              "CREATE TABLE map (id	INTEGER PRIMARY KEY, name	TEXT NOT NULL,notes	TEXT)");
          await db.execute(
              "CREATE TABLE profile (id	INTEGER PRIMARY KEY, name	TEXT NOT NULL, time	TEXT NOT NULL, rmb TEXT, is_checkout	INTEGER)");
        },
      );
      debugPrint("初始化数据库完成!");
    } catch (e) {
      debugPrint(e.toString());
    }
  }

  //增加 档案
  Future insProfile(Profile data) async {
    try {
      await db.insert(
        table,
        data.toMap(),
        // 如果插入的数据与已有数据冲突（例如，两个数据有相同的主键），则替换旧数据
        conflictAlgorithm: ConflictAlgorithm.replace,
      );
      return "插入${data.name}成功!";
    } catch (e) {
      // 打印错误信息
      debugPrint('插入错误信息: $e');
      return "[ERROR] - > ${e.toString()}";
    }
  }

  // 获取档案
  Future<List<Map<String, Object?>>> queryProfile() async {
    List<Map<String, Object?>> a = await db.query(table);
    return a;
  }

  // 更新档案
  Future updateProfile(Profile dx) async {
    try {
      await db.update(
        table,
        dx.toMap(),
        where: "id = ?",
        whereArgs: [dx.id],
      );
      debugPrint("更新数据->${dx.id}");
    } catch (e) {
      debugPrint("[ERROE]更新数据->$e}");
    }
  }

  Future<List<Map<String, Object?>>> queryMap() async {
    List<Map<String, Object?>> a = await db.query(mapTable);
    return a;
  }

  // 添加地点
  insMap(Maptable m) async {
    try {
      List list = await db.query(
        mapTable,
        where: "name = ?",
        whereArgs: [m.name],
      );

      if (list.isEmpty) {
        debugPrint("没有此用户");
        db.insert(
          mapTable,
          m.toMap(),
          // 如果插入的数据与已有数据冲突（例如，两个数据有相同的主键），则替换旧数据
          conflictAlgorithm: ConflictAlgorithm.replace,
        );
      }
    } catch (e) {
      debugPrint("[ERROE]添加地点->$e}");
    }
  }
}

class Maptable {
  final int? id;
  final String name; // 商户名称
  final String? notes; // 描述|注释
  Maptable({
    this.id,
    required this.name,
    this.notes,
  });

  Map<String, dynamic> toMap() {
    return {'id': id, 'name': name, 'notes': notes};
  }

  factory Maptable.fromMap(Map<String, dynamic> map) {
    return Maptable(name: map['name'], notes: map['notes']);
  }
}
